/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.lottery.game.core.modules.service.app.impl;

import com.google.common.collect.Maps;
import com.lottery.game.common.utils.UUIDUtils;
import com.lottery.game.core.modules.entity.game.CheckResult;
import com.lottery.game.core.modules.entity.user.GameUser;
import com.lottery.game.core.modules.entity.user.GameUserAccount;
import com.lottery.game.core.modules.entity.user.GameUserMoneyChange;
import com.lottery.game.core.modules.mapper.GameUserAccountDao;

import com.lottery.game.core.modules.mapper.GameUserDao;
import com.lottery.game.core.modules.mapper.GameUserMoneyChangeDao;
import com.lottery.game.core.modules.service.app.GameUserAccountService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 用户银行Service
 * @author dd
 * @version 2018-05-04
 */
@Service
@Slf4j
public class GameUserAccountServiceImpl implements GameUserAccountService {

	@Autowired
	private GameUserAccountDao gameUserAccountDao;

	@Autowired
	private GameUserMoneyChangeDao gameUserMoneyChangeDao;

	@Autowired
	private GameUserDao gameUserDao;


	/**
	 *
	 * 功能描述: 通过传入的信息判断是否已绑定过账户
	 *
	 * @param: GameUserAccount gameUserAccount
	 * @return: GameUserAccount gameUserAccount
	 * @auther: 1
	 * @date: 2019/4/3 16:05
	 */
	@Override
	public GameUserAccount getAccount(GameUserAccount gameUserAccount) {
		return this.gameUserAccountDao.getAccount(gameUserAccount);
	}
	@Override
	public GameUserAccount get(String id) {
		return this.gameUserAccountDao.get(id);
	}
	@Override
	public List<GameUserAccount> findList(GameUserAccount gameUserAccount) {
		return this.gameUserAccountDao.findList(gameUserAccount);
	}
	@Transactional(readOnly = false)
	@Override
	public void save(GameUserAccount gameUserAccount) {
		//新绑定是没有id的
		if(StringUtils.isEmpty(gameUserAccount.getId())){
			//新绑定
			gameUserAccount.setId(UUID.randomUUID().toString().replace("-",""));
			//加入时间
			gameUserAccount.setCreateDate(new Date());
			gameUserAccountDao.insert(gameUserAccount);
		} else {
			gameUserAccountDao.update(gameUserAccount);
		}
	}

	@Transactional(readOnly = false)
	@Override
	public void delete(GameUserAccount gameUserAccount) {
		this.gameUserAccountDao.delete(gameUserAccount);
	}

	/**
	 * 校验提现条件
	 *
	 * @param gameUser
	 * @return
	 */
	@Override
	public CheckResult getDownCheck(GameUser gameUser, String account) {
		boolean flag = false;
		BigDecimal value = new BigDecimal(account);
		// XXX 若以后添加了 userType 提现部分判断则需要修改
		String userType = gameUser.getUsertype();
		Map<String, Object> result = Maps.newHashMap();
		String msg = "提现成功,请等候";
		if (StringUtils.equals(userType, "2")) {
			//若为首充用户时 校验用户打码量是否达到标准
			result = this.checkActivityFirstChargeCodition(gameUser.getId());
			flag = (boolean) result.get("flag");
			msg = "首冲优惠用户打码量未满足条件";
		} else {
			flag = true;
		}
		CheckResult checkResult = new CheckResult(flag, msg, result);
		return checkResult;
	}

	/**
	 * 查询首冲优惠提现要求
	 */
	public Map checkActivityFirstChargeCodition(String userId) {
		GameUserMoneyChange tmp;

		List<String> betTypeList = new ArrayList<>();
		betTypeList.add("bet");
		betTypeList.add("cancelBet");
		List<String> gameUserList = new ArrayList<>();
		gameUserList.add(userId);
		List<GameUserMoneyChange> gameUserMoneyChangeList = gameUserMoneyChangeDao.findSimpleList(betTypeList, gameUserList, null, null, null);
		Double sum = 0d;
		for (int i = 0; i < gameUserMoneyChangeList.size(); i++) {
			sum = sum + Double.valueOf(gameUserMoneyChangeList.get(i).getChangeamt());
		}
		if (sum > 0) {
			log.error(String.format("%s下注金额%s异常", userId, sum));
		}
		//下注总量
		sum = Math.abs(sum);
		tmp = new GameUserMoneyChange();
		tmp.setGameUserId(userId);
		tmp.setBetType("activity_first_charge");
		List<GameUserMoneyChange> firstChargeList = gameUserMoneyChangeDao.findList(tmp);
		Map<String, Object> resultMap = Maps.newHashMap();
		resultMap.put("flag", false);
		if (firstChargeList.size() == 1) {
			String reason = firstChargeList.get(0).getChangereason();
			int startIndex = reason.indexOf("【");
			int endIndex = reason.indexOf("】");
			String[] firstChargeAmount = reason.substring(startIndex + 1, endIndex).split(":");
			//校验值 （首冲+奖金）*倍数
			Double value = (Double.valueOf(firstChargeAmount[0]) + Double.valueOf(firstChargeList.get(0).getChangeamt())) * Double.valueOf(firstChargeAmount[1]);
			if (sum > value) {
				resultMap.put("flag", true);
			}
			resultMap.put("sum",sum);
			resultMap.put("value",value);
		}
		return resultMap;
	}

	/**
	 * 更改用户余额，同时写一条暂扣余额的账变记录
	 *
	 * @param gameUser 用户
	 * @param change   余额改变的值
	 * @param reason   原因
	 */
	@Transactional
	@Override
	public void updateGameBalane(GameUser gameUser, Double change, String reason) {
		String oldBalance = gameUser.getBalance();
		String newBalance = Double.parseDouble(gameUser.getBalance()) - change + "";
		gameUser.setBalance(newBalance);
		gameUserDao.updateGameBalance(gameUser);
		//生成一条账变记录
		GameUserMoneyChange gameUserMoneyChange = new GameUserMoneyChange();
		gameUserMoneyChange.setBeforblnc(oldBalance);
		gameUserMoneyChange.setGameUserId(gameUser.getId());
		gameUserMoneyChange.setChangereason(reason);
		gameUserMoneyChange.setResultblnc(newBalance);
		gameUserMoneyChange.setChangeamt("-" + change.toString());
		gameUserMoneyChange.setChangetime(new Date(System.currentTimeMillis()));
		gameUserMoneyChange.setId(UUIDUtils.randomUUID());
		//TODO:账变类型整合
		gameUserMoneyChange.setBetType("downchange");
		gameUserMoneyChangeDao.insert(gameUserMoneyChange);
	}
}
